package com.lulin.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.lulin.common.utils.R;
import com.lulin.mall.product.entity.SkuImagesEntity;
import com.lulin.mall.product.entity.SpuInfoDescEntity;
import com.lulin.mall.product.fegin.SeckillFeginService;
import com.lulin.mall.product.service.*;
import com.lulin.mall.product.vo.SeckillVO;
import com.lulin.mall.product.vo.SpuItemVO;
import com.lulin.mall.product.vo.SkuItemSaleAttrVo;
import com.lulin.mall.product.vo.SpuItemGroupAttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lulin.common.utils.PageUtils;
import com.lulin.common.utils.Query;

import com.lulin.mall.product.dao.SkuInfoDao;
import com.lulin.mall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    SkuImagesService skuImagesService;
    //spu详细信息
    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    SkuInfoDao skuInfoDao;

    @Autowired
    SeckillFeginService seckillFeginService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * sku信息检索：根据多个条件，进行分页查询
     * 1、根据条件查询：分类、品牌、价格区间、模糊查询等
     * 2、分页查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        //关键字
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("sku_id", key)
                        .or().like("sku_name", key);
            });
        }
        //分类
        String catalogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
            wrapper.eq("catalog_id", catalogId);
        }
        //品牌
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        //价格区间(数据库表中只有1个价格字段-price)
        //最小价格
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            //ge：大于等于   le：小于等于
            wrapper.ge("price", min);
        }
        //最大价格
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            try {
                //如果max=0，那么，就不需要加这个条件了
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal(0)) == 1) {
                    //说明 max > 0
                    wrapper.le("price", max);
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
        }

        //分页查询
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据spuId,找到对应的sku信息
     *
     * @param spuId 商品skuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        //1个spu，有多sku，因此是list集合
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    /**
     * 根据skuId，查询对应的商品详情信息
     */
    @Override
    public SpuItemVO item(Long skuId) throws ExecutionException, InterruptedException {
        SpuItemVO spuItemVO = new SpuItemVO();
        //supplyAsync：创建1个异步操作，有异步处理结果
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            //1、sku的基本信息。pms_sku_info表
            SkuInfoEntity skuInfoEntity = getById(skuId);
            spuItemVO.setSkuInfo(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        //3、4、5步依赖于第1步，因此，使用thenXXX  thenAcceptAsync,可以拿到前面异步的结过，自己不会返回异步处理的结果
        CompletableFuture<Void> saleFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //3、获取spu中，销售属性的组合。
            List<SkuItemSaleAttrVo> saleAttrs =
                    skuSaleAttrValueService.getSkuSaleAttrValueBySpuId(res.getSpuId());
            spuItemVO.setSaleAttrs(saleAttrs);
        }, threadPoolExecutor);

        CompletableFuture<Void> spuFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //4、根据spuId，获取SPU的详细信息。
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            spuItemVO.setSpuInfoDesc(spuInfoDescEntity);
        }, threadPoolExecutor);

        CompletableFuture<Void> baseFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //5、spu的规格参数信息。
            //根据 SPU编号和CatalogId类别编号,查询出所有的属性组信息，根据属性组id关联查询到属性id，找到及其属性信息
            List<SpuItemGroupAttrVo> groupAttrVo =
                    attrGroupService.getAttrgroupWithSpuId(res.getSpuId(), res.getCatalogId());
            spuItemVO.setBaseAttrs(groupAttrVo);
        }, threadPoolExecutor);

        //runAsync：没有返回结果
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            //2、sku的图片信息。pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            spuItemVO.setSkuImages(images);
        }, threadPoolExecutor);

        //查询商品的秒杀活动
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeginService.getCurrentSeckillSkus(skuId);
            SeckillVO seckillVO = JSON.parseObject(r.get("data").toString(), SeckillVO.class);
            spuItemVO.setSeckillVO(seckillVO);
        }, threadPoolExecutor);

        //等待所有任务：等待这些任务全部完成
        CompletableFuture.allOf(saleFuture, spuFuture, imagesFuture, seckillFuture, baseFuture).get();
        return spuItemVO;
    }

    /**
     * 根据skuId，获取销售信息
     *
     * @param skuId 商品sku编号
     */
    @Override
    public List<String> getSkuSaleAttrs(Long skuId) {
        return skuInfoDao.getSkuSaleAttrs(skuId);
    }

}
